/**
 * Created on 10 avr. 08 by Sebastian Audet
 */
package grid;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeSet;

import tile.Tile;


/**
 * Implementation of a Node on a Grid
 * @author Sebastian Audet
 */
public class GridNode implements Node {
    
    private Location loc = null;
    private TreeSet<Tile> set = new TreeSet<Tile>();
    private boolean active = true;
    
    GridNode(Location loc)
    {
	this.loc=loc;
    }

    public boolean addTile(Tile tile) {
	return set.add(tile);
    }

    public boolean addTiles(TreeSet<Tile> set) {
	return set.addAll(set);
    }

    public boolean addTiles(Tile[] set) {
	return addTiles(tileArrayToTreeSet(set));
    }

    private TreeSet<Tile> tileArrayToTreeSet(Tile[] set) {
	TreeSet<Tile> rset = new TreeSet<Tile>();
	for(Tile t:set)
	{
	    rset.add(t);
	}
	return rset;
    }

    public void clearNode() {
	set=null;
    }

    public void clearNodeLevel(int level) {
	set.remove(returnLevel(level));
    }

    public boolean isActive() {
	return active;
    }

    public boolean removeTile(Tile tile) {
	return set.remove(tile);
    }

    public TreeSet<Tile> returnTiles() {
	return set;
    }

    public Tile[] returnArrayOfTiles() {
	ArrayList<Tile> t = new ArrayList<Tile>();
	Iterator<Tile> itr = set.iterator();
	while(itr.hasNext())
	{
	    t.add(itr.next());
	}
	return t.toArray(new Tile[t.size()]);
    }

    public void setActive(boolean b) {
	active=b;
    }

    public void setTiles(TreeSet<Tile> set) {
	this.set=set;
    }

    public void setTiles(Tile[] set) {
	TreeSet<Tile> temp = new TreeSet<Tile>();
	for(Tile t:set)
	{
	    temp.add(t);
	}
	this.set=temp;
    }

    public int tileCount() {
	return set.size();
    }

    public void toggle() {
	setActive(!active);
    }

    public void turnOff() {
	active = false;
    }

    public void turnOn() {
	active = true;
    }

    public Tile returnLevel(int level) {
	for(Tile t:returnArrayOfTiles())
	{
	    if(level==t.getLevel())
	    {
		return t;
	    }
	}
	return null;
    }

    public Location getLocation() {
	return loc;
    }

    public void setLocation(Location location) {
	this.loc = location;
    }

    public boolean isEmpty(int level) {
	if(returnLevel(level)==null)
	{
	    return true;
	}
	else
	{
	    return false;
	}
    }

    public int compareTo(Node o) {
	return getLocation().compareTo(o.getLocation());
    }
    
}
